package com.sychip.fhc.app.wsn.screen

import android.content.res.Configuration
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropUp
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.FilterList
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.SearchBar
import androidx.compose.material3.SearchBarDefaults
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.fhc.base.LocalManager.stringResource
import com.fhc.base.isTablet
import com.fhc.base.noStyle
import com.fhc.view.CircleTextView
import com.fhc.view.FhcRangeSlider
import com.fhc.view.alphaAnim
import com.fhc.view.utils.BottomCornersShape
import com.fhc.view.utils.Hint
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.app.wsn.common.util.rssiColor
import kotlinx.coroutines.delay

const val RssiMin = -110f
const val RssiMax = 0f
data class FilterDto(
    val devIds: String = "",
    val isFilterDevIds: Boolean = false,
    val rssiRangeMin: Float = RssiMin,
    val rssiRangeMax: Float = RssiMax,
    val isFilterRssi: Boolean = false,
)

@Preview(showBackground = true)
@Composable
fun HexInputField(
    modifier: Modifier = Modifier,
    value: String ="",
    onValueChange: (String) -> Unit={},
    label: String="",
    prefix: String="0x",
    enabled: Boolean = true,
    isError: Boolean = false,
    errorMessage: String? = null,
    maxLength: Int = 4,
    keyboardType: KeyboardType = KeyboardType.Password,
    imeAction: ImeAction = ImeAction.Next
) {
    val borderColor = colorResource(id = android.R.color.darker_gray)
    val errorColor = colorScheme.error
    val focusManager = LocalFocusManager.current
    val focusRequester = remember { FocusRequester() }

    OutlinedTextField(
        modifier = modifier,
        enabled = enabled,
        value = value,
//        textStyle = if (value.isEmpty()) {
//            LocalTextStyle.current.copy(color = Color.Gray) // 空状态颜色
//        } else {
//            LocalTextStyle.current.copy(color = Color.Black) // 有内容时的颜色
//        },

        onValueChange = { newValue ->
            val filteredValue = newValue.uppercase().filter { it in '0'..'9' || it in 'A'..'F' }
            onValueChange(filteredValue.take(maxLength))
        },
        prefix = { // 自定义左侧内容
           if(prefix.isNotEmpty()) Text(prefix, color = Color.Gray)
        },
        label = {
            Text( text = label, color = borderColor )
        },
        keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Characters,  // 强制大写
            autoCorrectEnabled = false,  // 禁用自动修正
            keyboardType = keyboardType,  // 或使用 KeyboardType.Password 隐藏输入内容
            imeAction = imeAction
        ),
        isError = isError,
        supportingText = {
            if (isError && !errorMessage.isNullOrEmpty()) {
                Text(
                    text = errorMessage,
                    color = colorScheme.error
                )
            }
        },
        trailingIcon = {
            if (value.isNotEmpty() && enabled) {
                Icon(
                    imageVector = Icons.Filled.Clear,
                    contentDescription = "Clear",
                    modifier = Modifier.clickable {
                        focusManager.clearFocus()  // 清除当前焦点
                        focusRequester.requestFocus() //
                        onValueChange("")
                    },
                    tint = Color.Gray
                )
            }
        },
//        placeholder = {
//            Text(
//                label,
//                color = Color.LightGray.copy(alpha = 0.7f)
//            )
//        },
        singleLine = true,
        shape = MaterialTheme.shapes.extraSmall,
        colors = OutlinedTextFieldDefaults.colors(
            unfocusedContainerColor = Color.Transparent,
            focusedContainerColor = Color.Transparent,
            errorContainerColor = Color.Transparent,
            focusedBorderColor = if (isError) errorColor else borderColor,
            unfocusedBorderColor = if (isError) errorColor else borderColor,
            errorBorderColor = errorColor,
            disabledBorderColor = if (isError) errorColor else borderColor.copy(alpha = 0.3f),
            cursorColor = if (isError) errorColor else colorScheme.primary,
//            errorPlaceholderColor = errorColor,
//            disabledPlaceholderColor = Color.Gray,
//            focusedPlaceholderColor = Color.Gray.copy(alpha = 0.3f),
//            unfocusedPlaceholderColor = Color.Gray,
//            errorLabelColor = Color.Blue,
//            disabledLabelColor = Color.Blue.copy(alpha = 0.3f),
//            focusedLabelColor = Color.Blue.copy(alpha = 0.3f),
//            unfocusedLabelColor = Color.Blue.copy(alpha = 0.3f),

        )
    )
}
@Preview
@Composable
internal fun RssiEmptyView(modifier: Modifier = Modifier) {
    Box(modifier = modifier.fillMaxSize()){
        Column(
            modifier = modifier.wrapContentSize().align(Alignment.Center),
            verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
//            Image(
//                painter = rememberVectorPainter(image = Icons.AutoMirrored.Filled.BluetoothSearching),
//                contentDescription = null,
//                modifier = Modifier.size(80.dp),
//                colorFilter = ColorFilter.tint(colorScheme.onPrimaryContainer.copy(alpha = 0.6f)),
//            )
            CircleTextView(text = "RSSI", sizeDp = 96.dp, backgroundColor = colorScheme.onPrimaryContainer.copy(alpha = 0.3f))
            Text(text = stringResource(id = R.string.wsn_no_device_data_title), color  =colorScheme.primary, fontWeight = FontWeight.ExtraBold)
            Hint(text = stringResource(id = R.string.wsn_no_device_data_info).noStyle(), textAlign = TextAlign.Center)
        }
    }
}

//@Composable
//internal fun HeartBeatAnimation() {
//    var isBeating by remember { mutableStateOf(false) }
//    val scale by animateFloatAsState(
//        targetValue = if (isBeating) 1.2f else 1f,
//        animationSpec = keyframes {
//            durationMillis = 1000
//            0.0f at 0 using LinearEasing
//            1.2f at 300 using FastOutSlowInEasing
//            1.0f at 700 using LinearEasing
//        },
//        label = "heart_scale"
//    )
//
//    LaunchedEffect(Unit) {
//        while (true) {
//            isBeating = !isBeating
//            delay(1500)
//        }
//    }
//
//    Icon(
//        imageVector = Icons.Filled.Favorite,
//        contentDescription = "心跳图标",
//        modifier = Modifier.size(64.dp).graphicsLayer {
//                scaleX = scale
//                scaleY = scale
//            },
//        tint = colorScheme.error
//    )
//
//}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FilterContent(query: String, regex: Regex?, onQueryChange: (searchQuery:String)->Unit = {}, onBackgroundClick: ()->Unit = {} ){
    val focusManager = LocalFocusManager.current
    // 使用派生状态确保外部query更新同步到内部
    var searchQuery by remember(query) { mutableStateOf(query) }

    // 防抖核心逻辑：300ms延迟触发回调
    LaunchedEffect(searchQuery) {
        if (searchQuery != query) { // 避免初始值重复触发
            delay(300)
            onQueryChange(searchQuery)
        }
    }

    Box(modifier = Modifier.fillMaxSize()){
        Box(modifier = Modifier.fillMaxSize().background(color = Color.Black.copy(alpha = 0.6f)).clickable(
            onClick = {
                focusManager.clearFocus()
                onBackgroundClick()
            }
        )){
        }
        SearchBar(
            modifier = Modifier.align(Alignment.TopCenter),
            windowInsets = WindowInsets(0.dp),
            inputField = {
                SearchBarDefaults.InputField(
                    query = searchQuery,
                    onQueryChange = {
                        searchQuery = (regex?.replace(it, "") ?: it).uppercase().take(20)
                    },
                    onSearch = {
                        focusManager.clearFocus()
                        onBackgroundClick()
                    },
                    expanded = false,
                    onExpandedChange = {   },
                    placeholder = { Text(stringResource(R.string.wsn_info_input_dev_id)) },
                    leadingIcon = { Icon(Icons.Default.Search, contentDescription = null,
                        modifier = Modifier.clickable {
                            focusManager.clearFocus()
                            onBackgroundClick()
                        }) },
                    trailingIcon = {
                        if (!searchQuery.isEmpty()) {
                            Icon(
                                Icons.Default.Close, contentDescription = null,
                                modifier = Modifier.clickable {
                                    searchQuery = ""
//                                    onClearQuery()
                                    focusManager.clearFocus()
                                })
                        }
                    },
                )
            },
            expanded = false,
            onExpandedChange = {  },
        ) {

        }
    }
}


@Composable
fun FilterRow(
    showFilterTop: Boolean,
    searchQuery: String,
    onDismiss: () -> Unit
) {
    // 1. 动画状态管理
    var visible by remember { mutableStateOf(showFilterTop) }
    val offsetY by animateFloatAsState(
        targetValue = if (visible) 0f else -100f,
        animationSpec = tween(durationMillis = 300),
        finishedListener = { if (!visible) onDismiss() }
    )

    // 2. 自动触发隐藏动画
    LaunchedEffect(key1=showFilterTop, key2= searchQuery) {
        if (searchQuery.trim().isEmpty()) {
            visible = false
        } else {
            visible = true
            visible = showFilterTop
        }
    }

    // 3. 动画布局实现
    AnimatedVisibility(
        visible = visible,
        enter = fadeIn(),
        exit = slideOutVertically { -it },
        modifier = Modifier.offset(y = offsetY.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.Black.copy(alpha = 0.8f)),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "Filter: $searchQuery",
                modifier = Modifier.weight(1f),
                color = Color.White,
                textAlign = TextAlign.Center
            )
            IconButton(
                onClick = { visible = false }
            ) {
                Icon(
                    imageVector = Icons.Default.Close,
                    contentDescription = "关闭",
                    tint = Color.White
                )
            }
        }
    }
}

 val FilterHeight =  54.dp

@Preview(showBackground = true)
@Composable
fun MultipleFilterRow(
    modifier: Modifier = Modifier,
    isExpanded: MutableState<Boolean> = remember { mutableStateOf(false) },
    filter: FilterDto = FilterDto(),
    filterResult: String ="",
    onFilterChanged: (FilterDto) -> Unit = {},
    onFilterCollapseStart: (Boolean) -> Unit = {},
    onFilterCollapseStop: (Boolean) -> Unit = {}
) {
    val focusManager = LocalFocusManager.current

//    val rotation by animateFloatAsState(
//        targetValue = if (isExpanded.value) 180f else 0f,
//        animationSpec = tween(durationMillis = 300),
//        label = "icon_rotation", finishedListener = {
//            onFilterExpand(!isExpanded.value)
//        }
//    )
    // 使用 Animatable 替代 animateFloatAsState
    val rotation = remember { Animatable(0f) }

    // 动画启动副作用
    LaunchedEffect(isExpanded.value) {
        val targetRotation = if (isExpanded.value) 180f else 0f

        onFilterCollapseStart(!isExpanded.value)
        rotation.animateTo(
            targetRotation,
            animationSpec = tween(durationMillis = 300)
        ) {
            onFilterCollapseStop(!isExpanded.value)
        }
    }

    Column(modifier = modifier){
        Row(
            modifier = Modifier.fillMaxWidth().height(FilterHeight).background(Color.Black).clickable(onClick = { isExpanded.value =!isExpanded.value }),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {

            Box(modifier = Modifier.padding(start = 15.dp)){
                Icon(
                    Icons.Filled.FilterList,
                    contentDescription = null,
                    modifier = Modifier.size(28.dp),
                    tint = Color.White
                )
                if (filter.isFilterDevIds || filter.isFilterRssi) {
                    Box(
                        modifier = Modifier.alphaAnim(600)
                            .align(Alignment.TopEnd).size(10.dp)
                            .background(colorScheme.primary, CircleShape)
                    )
                }
            }
            Text(
                text = if (filter.isFilterDevIds || filter.isFilterRssi) stringResource(R.string.wsn_filter_active, filterResult) else stringResource(R.string.wsn_filter_inactive, filterResult),
                fontWeight = FontWeight.Bold,
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.weight(1f).padding(10.dp),
                color = Color.White,
                textAlign = TextAlign.Start
            )

            Icon(Icons.Filled.ArrowDropUp, stringResource(id = R.string.menu_more),modifier = Modifier.padding(end = 10.dp)
                .size(32.dp).graphicsLayer {
                    rotationZ = rotation.value
                },  tint=Color.Red)
        }
        // 3. 动画布局实现
        AnimatedVisibility(
                visible = isExpanded.value,
                enter = expandVertically() + fadeIn(),
                exit = shrinkVertically() + fadeOut()
            ) {
            Column(modifier = Modifier.clickable(
                onClick = { focusManager.clearFocus() }
            ),){
                Box(
                    modifier = Modifier.fillMaxWidth().height(2.dp)
                        .background(
                            brush = Brush.horizontalGradient(
                                colors = listOf(
                                    Color.DarkGray,
                                    Color.Black,
                                    Color.DarkGray,
                                )
                            )
                        )
                )
                FilterDtoContent(filter,onFilterChanged)
            }
        }

        Row(modifier = Modifier.fillMaxWidth().weight(1f).background(Color.Transparent).then(if(isExpanded.value) Modifier.clickable(
            onClick = {
                isExpanded.value = false
                focusManager.clearFocus()
            }
        ) else Modifier )){

        }
    }
}


@Preview(showBackground = true)
@Composable
fun  FilterDtoContent(filter: FilterDto = FilterDto(), onFilterChanged: (FilterDto) -> Unit = {}, autoEnable: Boolean = true ){
    val focusManager = LocalFocusManager.current
    var devIds by remember { mutableStateOf(filter.devIds) }
    val config = LocalConfiguration.current
    val isMini = config.orientation == Configuration.ORIENTATION_PORTRAIT && !isTablet()
    //devIds变化后，viewmodel更新prefStore耗时，如果输入太快会导致光标移动不及时导致输入框位置错误，所以用临时变量
    //其他item不涉及手动输入，影响不大

    val modifier = Modifier.fillMaxWidth().
    shadow(elevation = 12.dp, shape = BottomCornersShape(8.dp), clip = true, spotColor = colorScheme.primary).  //外层设置blur，没必要shadow
    background(Color.Black,BottomCornersShape(2.dp))
    if(!isMini) modifier.padding(start = 50.dp, end = 40.dp, top = 10.dp, bottom = 20.dp)
    else modifier.padding(start = 10.dp, end = 10.dp, top = 10.dp, bottom = 10.dp)
    Column( modifier = modifier,
        verticalArrangement = Arrangement.spacedBy(10.dp) // 设置行间距为 10.dp
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(if(!isMini) 20.dp else 0.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(modifier = Modifier.align(alignment=Alignment.CenterVertically).widthIn(min = 140.dp),
                textAlign = TextAlign.End, fontSize = 16.sp, text = stringResource(R.string.wsn_filter_ids), maxLines = 1)

            TextField(
                modifier = Modifier.fillMaxWidth().weight(1f).padding(start = 10.dp, end = 10.dp),
                textStyle = TextStyle(color = Color.White),
                value = devIds,
                onValueChange = { it ->
                    devIds =  (Regex("[^a-zA-Z0-9 ]").replace(it, "")).uppercase().take(20)

                    if(autoEnable) onFilterChanged(filter.copy(devIds = devIds, isFilterDevIds = devIds.isNotEmpty()))
                    else onFilterChanged(filter.copy(devIds = devIds))
                },
                keyboardOptions = KeyboardOptions(capitalization = KeyboardCapitalization.Characters,  // 强制大写
                    autoCorrectEnabled = false,  // 禁用自动修正
                    keyboardType = KeyboardType.Password,  // 或使用 KeyboardType.Password 隐藏输入内容
                    imeAction = ImeAction.Done
                ),
                isError = false,
                trailingIcon = {
                    if(!devIds.isEmpty()){
                        Icon( Icons.Filled.Close, null, tint = Color.White,
                            modifier = Modifier.clickable(
                                onClick = {
                                    devIds = ""
                                    if(autoEnable) onFilterChanged(filter.copy(devIds = devIds, isFilterDevIds = devIds.isNotEmpty()))
                                    else onFilterChanged(filter.copy(devIds = devIds))
                                }
                            ).size(16.dp)
                        )
                    }
                },
                singleLine = true,
                colors = TextFieldDefaults.colors(
                    unfocusedContainerColor = Color.Transparent,
                    focusedContainerColor = Color.Transparent,
                    errorContainerColor = Color.Transparent,
                    cursorColor = colorScheme.primary
                )
            )
            Switch(modifier = Modifier.padding(end=10.dp),checked = filter.isFilterDevIds, onCheckedChange = {
                focusManager.clearFocus()
                onFilterChanged(filter.copy(isFilterDevIds = it))
            })
        }
        val  rssiRangeStr = buildAnnotatedString {

            // 添加红色数字部分
            withStyle(style = SpanStyle(color = filter.rssiRangeMin.toInt().rssiColor(), fontSize = 16.sp,  fontWeight = FontWeight.Bold)) {
                append("${filter.rssiRangeMin.toInt()}")
            }
            withStyle(style = SpanStyle(fontSize = 12.sp  )) {
                append("dBm ~ ")
            }

            withStyle(style = SpanStyle(color = filter.rssiRangeMax.toInt().rssiColor(), fontSize = 16.sp,  fontWeight = FontWeight.Bold)) {
                append("${filter.rssiRangeMax.toInt()}")
            }
            withStyle(style = SpanStyle(fontSize = 12.sp)) {
                append("dBm")
            }
        }
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(if(!isMini) 20.dp else 0.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(modifier = Modifier.align(alignment=Alignment.CenterVertically).widthIn(min = 140.dp),
                textAlign = TextAlign.End, text = rssiRangeStr, maxLines = 1)
            FhcRangeSlider(
                modifier = Modifier.fillMaxWidth().weight(1f).padding(start=10.dp, end=10.dp),
                value = (filter.rssiRangeMin..filter.rssiRangeMax),
                onValueChange = {
                    focusManager.clearFocus()
                    if(autoEnable) onFilterChanged(filter.copy(rssiRangeMin = it.start,  rssiRangeMax= it.endInclusive, isFilterRssi = true))
                    else onFilterChanged(filter.copy(rssiRangeMin = it.start,  rssiRangeMax= it.endInclusive))
                },
                valueRange = RssiMin..RssiMax,
            )
            Switch(modifier = Modifier.padding(end=10.dp),checked = filter.isFilterRssi, onCheckedChange = {
                focusManager.clearFocus()
                onFilterChanged(filter.copy(isFilterRssi = it))
            })
        }
    }
}
